# uncompyle6 version 3.2.3
# Python bytecode 3.6 (3379)
# Decompiled from: Python 3.6.8 |Anaconda custom (64-bit)| (default, Feb 21 2019, 18:30:04) [MSC v.1916 64 bit (AMD64)]
# Embedded file name: site-packages\ntlm_auth\compute_hash.py
import binascii, hashlib, hmac, re
from ntlm_auth import des


def _lmowfv1(password):
    """
    [MS-NLMP] v28.0 2016-07-14
    
    3.3.1 NTLM v1 Authentication
    Same function as LMOWFv1 in document to create a one way hash of the password. Only
    used in NTLMv1 auth without session security
    
    :param password: The password or hash of the user we are trying to authenticate with
    :return res: A Lan Manager hash of the password supplied
    """
    if re.match("^[a-fA-F\\d]{32}:[a-fA-F\\d]{32}$", password):
        lm_hash = binascii.unhexlify(password.split(":")[0])
        return lm_hash
    else:
        password = password.upper()
        lm_pw = password[0:14]
        magic_str = b"KGS!@#$%"
        res = b""
        dobj = des.DES(lm_pw[0:7])
        res = res + dobj.encrypt(magic_str)
        dobj = des.DES(lm_pw[7:14])
        res = res + dobj.encrypt(magic_str)
        return res


def _ntowfv1(password):
    """
    [MS-NLMP] v28.0 2016-07-14
    
    3.3.1 NTLM v1 Authentication
    Same function as NTOWFv1 in document to create a one way hash of the password. Only
    used in NTLMv1 auth without session security
    
    :param password: The password or hash of the user we are trying to authenticate with
    :return digest: An NT hash of the password supplied
    """
    if re.match("^[a-fA-F\\d]{32}:[a-fA-F\\d]{32}$", password):
        nt_hash = binascii.unhexlify(password.split(":")[1])
        return nt_hash
    else:
        digest = hashlib.new("md4", password.encode("utf-16le")).digest()
        return digest


def _ntowfv2(user_name, password, domain_name):
    """
    [MS-NLMP] v28.0 2016-07-14
    
    3.3.2 NTLM v2 Authentication
    Same function as NTOWFv2 (and LMOWFv2) in document to create a one way hash of the password.
    This combines some extra security features over the v1 calculations used in NTLMv2 auth.
    
    :param user_name: The user name of the user we are trying to authenticate with
    :param password: The password of the user we are trying to authenticate with
    :param domain_name: The domain name of the user account we are authenticated with
    :return digest: An NT hash of the parameters supplied
    """
    digest = _ntowfv1(password)
    digest = hmac.new(
        digest, (user_name.upper() + domain_name).encode("utf-16le")
    ).digest()
    return digest
